package c2;

/**
 * 指令重排序测试
 * 输出结果不一定是期望的4，因为(3)执行后可能(4)还未执行就执行了(1)
 */
public class ReorderTest {
    private static int num=0;
    private static boolean ready=false;
    public static class ReadThread extends Thread{
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()){
                if(ready){ //(1)
                    System.out.println(num+num); //(2)
                }
                System.out.println("read thread...");
            }
        }
    }

    public static class WriteThread extends Thread{
        @Override
        public void run() {
            num=2;  //(3)
            ready=true; //(4)
            System.out.println("writeThread set over...");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread read=new ReadThread();
        read.start();
        Thread write=new WriteThread();
        write.start();
        Thread.sleep(5);
        read.interrupt();
        System.out.println("main exit");
    }


}
